﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Reflection;


namespace Sita.Data.Core
{
    public class RepositoryHelper<T> where T : class, new()
    {
        public Type GetPropertyType(string propertyName)
        {
            System.Reflection.PropertyInfo EntityProperty;
            string[] Properties = propertyName.Split('.');
            EntityProperty = typeof(T).GetProperty(Properties[0]);

            for (int i = 1; i < Properties.Length; i++)
            {
                EntityProperty = EntityProperty.PropertyType.GetProperty(Properties[i]);
            }

            return EntityProperty.PropertyType;
        }

        public dynamic GetOrderExpression(string sortColumn)
        {
            MethodInfo CurrentMethod;

            CurrentMethod = this.GetType().GetMethod("GetOrderExpressionByKnownType").MakeGenericMethod(
                new Type[] { GetPropertyType(sortColumn) });

            var ReturnObject = CurrentMethod.Invoke(this, new object[] { sortColumn }) as dynamic;

            return ReturnObject;
        }

        public Expression<Func<T, S>> GetOrderExpressionByKnownType<S>(string sortColumn)
        {
            var ColumnParam = Expression.Parameter(typeof(T), "p");

            string[] Properties = sortColumn.Split('.');
            MemberExpression ExpressionProperty = Expression.Property(ColumnParam, Properties[0]);

            for (int i = 1; i < Properties.Length; i++)
            {
                ExpressionProperty = Expression.Property(ExpressionProperty, Properties[i]);
            }

            return Expression.Lambda<Func<T, S>>(ExpressionProperty, ColumnParam);
        }
    }
}
